using System;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Xunit;

namespace muduoDotNet.Tests
{
    public class TcpServerTest
    {
        [Fact]
        public void TestTcpServerCreation()
        {
            var loop = new EventLoop();
            var server = new TcpServer(loop, new IPEndPoint(IPAddress.Any, 0));
            
            Assert.NotNull(server);
            Assert.Equal(0, server.ConnectionCount);
            
            server.Dispose();
            loop.Dispose();
        }

        [Fact]
        public void TestTcpServerStartStop()
        {
            var loop = new EventLoop();
            var server = new TcpServer(loop, new IPEndPoint(IPAddress.Any, 0));
            
            // 启动服务器
            server.Start();
            
            // 停止服务器
            server.Stop();
            
            server.Dispose();
            loop.Dispose();
        }

        [Fact]
        public void TestTcpServerWithCallback()
        {
            var loop = new EventLoop();
            var server = new TcpServer(loop, new IPEndPoint(IPAddress.Loopback, 19999));
            
            bool connectionCallbackCalled = false;
            bool messageCallbackCalled = false;
            
            server.ConnectionCallback = (conn) =>
            {
                connectionCallbackCalled = true;
            };
            
            server.MessageCallback = (conn, buffer) =>
            {
                messageCallbackCalled = true;
                var message = buffer.ReadAllString();
                conn.Send($"Echo: {message}");
            };
            
            server.Start();
            
            // 在后台运行事件循环
            var loopTask = Task.Run(() =>
            {
                loop.Start();
            });
            
            Thread.Sleep(100); // 让服务器启动
            
            // 注意：由于异步性质，这些断言可能不会立即通过
            // 在实际测试中，可能需要更复杂的同步机制
            
            server.Stop();
            loop.Stop();
            
            loopTask.Wait(1000);
            
            server.Dispose();
            loop.Dispose();
            
            // 由于没有真正的客户端连接，这些断言可能会失败
            // Assert.True(connectionCallbackCalled);
            // Assert.True(messageCallbackCalled);
        }
    }
}